<?php

namespace App\Http\Controllers;

use App\Http\Requests\WikiCreateRequest;
use App\WikiRevision;
use Illuminate\Http\Request;
use App\Wiki;
use App\Category;
use Auth;
use Mews\Purifier\Facades\Purifier;
use App\Services\WikiActivityLogService;
class WikisController extends Controller
{
    protected $activityLog;
    public function __construct(WikiActivityLogService $activityLog)
    {
        $this->middleware('auth')->except('index', 'show');
        $this->activityLog = $activityLog;
    }

    public function index(Wiki $wiki)
    {
        $wikis = $wiki->paginate(10);
        return view('wikis.index', compact('wikis'));
    }

    public function show(Wiki $wiki)
    {
        if ($revision = $wiki->getCurrentRevision())
        {
            $revision->is_default_version = true;
        }
        $wiki->loadMissing('likers', 'subscribers');
        $comments = $wiki->comments()->paginate(10);
        $wiki_logs = $this->activityLog->getLogs($wiki);

        return view('wikis.show', compact('wiki', 'revision', 'comments', 'wiki_logs'));
    }
    public function create()
    {
        return view('wikis.create');
    }

    public function store(Wiki $wiki, WikiCreateRequest $request)
    {
        $wiki->fill($request->all());
        $wiki->founder_id = Auth::id();
        $wiki->save();
        $this->activityLog->created($wiki, Auth::user());
        return redirect()->route('wikis.show', $wiki->id)->with('success', '词条创建成功');
    }

    public function edit(Wiki $wiki, WikiRevision $version = null)
    {
        if ($wiki->frozen_at) {
            return redirect()->back()->with('warning', '该词条已被锁定，禁止编辑');
        }
        $categories = Category::with('children')->root()->get();
        $revision = $wiki->getCurrentRevision();
        return view('wikis.create_and_edit', compact('wiki', 'categories', 'revision', 'version'));
    }

    public function update(Wiki $wiki, Request $request, WikiRevision $revision = null)
    {
        $isChange = $this->checkChange($wiki, $request, $revision);
        if ( ! $isChange) {
            return redirect()->back()->with('warning', '未做任何修改！');

        } else if($revision) {
            $revision->fill($request->all());
            $revision->user_id = auth()->id;
            $revision->save();
            return redirect()->route('wikis.show', ['wiki' => $wiki->id, 'version' => $revision->id])->with('success', '成功修改过一个版本');
        }else {
            $revision = $this->createNewRevision($wiki);
            $revision->fill($request->all());
            $revision->save();
            return redirect()->route('wikis.show', ['wiki' => $wiki->id])->with('success', '成功提交一个版本');
        }
    }

    public function set(Wiki $wiki, Request $request)
    {
        $type = $request->type;
        if (in_array($type, ['excellent', 'pinned', 'frozen', 'banned'])) {
            if(!$wiki->getAttribute($type . '_at')) {
                $wiki->update([
                    $type . '_at' => now()
                ]);
            } else {
                $wiki->update([
                    $type . '_at' => null
                ]);
            }
        }
        return redirect()->back();
    }

    protected function checkChange($wiki, $request, $version = null)
    {
        if (!$version) {
            $version = $wiki->getCurrentRevision();
        }
        $oldCategories = $version->categories->pluck('id')->toArray();
        $requestCategory = explode(',', $request->category);
        $newCategories = collect($requestCategory)->map(function ($i, $key) {
            return (int) $i;
        })->toArray();
        $titleChange = $wiki->title !== $request->title;
        $contentChange = $version->content->body !== Purifier::clean($request->body);
        $categoryChange = $oldCategories !== $newCategories;
        if (!$titleChange && !$contentChange && !$categoryChange) {
            return false;
        }
        return true;
    }

    protected function createNewRevision(Wiki $wiki)
    {
        return $revision = $wiki->revisions()->create([
                'user_id' => Auth::id(),
        ]);
    }
}
